/**
 * Laypage 分页组件
 */
import "./laypage.css";

class LaypageClass {
    constructor(options) {
        let that = this;
        that.config = options || {};
        that.config.index = ++Laypage.index;
        that.render(true);
    }

    /**
     *判断传入的容器类型
     * @returns
     */
    type() {
        var config = this.config;
        if (typeof config.elem === "object") {
            return config.elem.length === undefined ? 2 : 3;
        }
    }

    /**
     * 页视图
     * @returns
     */
    view = function () {
        var that = this;
        var config = that.config;

        // 连续页码个数
        var groups = (config.groups = "groups" in config ? Number(config.groups) || 0 : 5);

        // 排版
        config.layout = typeof config.layout === "object" ? config.layout : ["prev", "page", "next"];

        config.count = Number(config.count) || 0; // 数据总数
        config.curr = Number(config.curr) || 1; // 当前页

        // 每页条数的选择项
        config.limits = typeof config.limits === "object" ? config.limits : [10, 20, 30, 40, 50];

        // 默认条数
        config.limit = Number(config.limit) || 10;

        // 总页数
        config.pages = Math.ceil(config.count / config.limit) || 1;

        // 当前页不能超过总页数
        if (config.curr > config.pages) {
            config.curr = config.pages;
        } else if (config.curr < 1) {
            // 当前分页不能小于 1
            config.curr = 1;
        }

        // 连续分页个数不能低于 0 且不能大于总页数
        if (groups < 0) {
            groups = 1;
        } else if (groups > config.pages) {
            groups = config.pages;
        }

        config.prev = "prev" in config ? config.prev : "上一页"; // 上一页文本
        config.next = "next" in config ? config.next : "下一页"; // 下一页文本

        // 计算当前组
        var index = config.pages > groups ? Math.ceil((config.curr + (groups > 1 ? 1 : 0)) / (groups > 0 ? groups : 1)) : 1;

        // 视图片段
        var views = {
            // 上一页
            prev: (function () {
                console.log("ffdsafsd");
                return config.prev ? '<a class="laypage-prev' + (config.curr == 1 ? " " + "laypage-disabled" : "") + '" data-page="' + (config.curr - 1) + '">' + config.prev + "</a>" : "";
            })(),

            // 页码
            page: (function () {
                var pager = [];

                // 数据量为0时，不输出页码
                if (config.count < 1) {
                    return "";
                }

                // 首页
                if (index > 1 && config.first !== false && groups !== 0) {
                    pager.push('<a class="laypage-first" data-page="1"  title="首页">' + (config.first || 1) + "</a>");
                }

                // 计算当前页码组的起始页
                var halve = Math.floor((groups - 1) / 2); // 页码数等分
                var start = index > 1 ? config.curr - halve : 1;
                var end =
                    index > 1
                        ? (function () {
                              var max = config.curr + (groups - halve - 1);
                              return max > config.pages ? config.pages : max;
                          })()
                        : groups;

                // 防止最后一组出现“不规定”的连续页码数
                if (end - start < groups - 1) {
                    start = end - groups + 1;
                }

                // 输出左分割符
                if (config.first !== false && start > 2) {
                    pager.push('<span class="laypage-spr">...</span>');
                }

                // 输出连续页码
                for (; start <= end; start++) {
                    if (start === config.curr) {
                        // 当前页
                        pager.push('<span class="laypage-curr"><em class="laypage-em" ' + (/^#/.test(config.theme) ? 'style="background-color:' + config.theme + ';"' : "") + "></em><em>" + start + "</em></span>");
                    } else {
                        pager.push('<a data-page="' + start + '">' + start + "</a>");
                    }
                }

                // 输出输出右分隔符 & 末页
                if (config.pages > groups && config.pages > end && config.last !== false) {
                    if (end + 1 < config.pages) {
                        pager.push('<span class="laypage-spr">...</span>');
                    }
                    if (groups !== 0) {
                        pager.push('<a class="laypage-last" title="尾页"  data-page="' + config.pages + '">' + (config.last || config.pages) + "</a>");
                    }
                }

                return pager.join("");
            })(),

            // 下一页
            next: (function () {
                return config.next ? '<a class="laypage-next' + (config.curr == config.pages ? " " + "laypage-disabled" : "") + '" data-page="' + (config.curr + 1) + '">' + config.next + "</a>" : "";
            })(),

            // 数据总数
            count: (function () {
                var countText = typeof config.countText === "object" ? config.countText : ["共 ", " 条"];
                return '<span class="laypage-count">' + countText[0] + config.count + countText[1] + "</span>";
            })(),

            // 每页条数
            limit: (function () {
                var elemArr = ['<span class="laypage-limits"><select lay-ignore>'];
                var template = function (item) {
                    var def = item + " 条/页";
                    return typeof config.limitTemplet === "function" ? config.limitTemplet(item) || def : def;
                };

                // 条目选项列表
                config.limits.forEach((item,index) => {
                    elemArr.push('<option value="' + item + '"' + (item === config.limit ? " selected" : "") + ">" + template(item) + "</option>");
                });

                return elemArr.join("") + "</select></span>";
            })(),

            // 刷新当前页
            refresh: ['<a data-page="' + config.curr + '" class="laypage-refresh">', '<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="200" height="200"><path d="M866.133333 85.333333c4.693333 0 8.533333 3.84 8.533334 8.533334v194.133333a32 32 0 0 1-28.928 31.850667L842.666667 320h-194.133334a8.533333 8.533333 0 0 1-8.533333-8.533333v-46.933334c0-4.693333 3.84-8.533333 8.533333-8.533333h120.341334A361.536 361.536 0 0 0 512 149.333333C311.701333 149.333333 149.333333 311.701333 149.333333 512s162.368 362.666667 362.666667 362.666667c185.813333 0 339.008-139.776 360.170667-319.914667 0.384-3.328 0.810667-7.829333 1.28-13.546667a8.533333 8.533333 0 0 1 8.512-7.850666h47.061333a8.533333 8.533333 0 0 1 8.533333 9.109333c-0.426667 5.696-0.789333 10.218667-1.130666 13.589333C914.346667 770.986667 732.778667 938.666667 512 938.666667 276.352 938.666667 85.333333 747.648 85.333333 512S276.352 85.333333 512 85.333333c116.288 0 221.717333 46.506667 298.666667 121.984V93.866667c0-4.693333 3.84-8.533333 8.533333-8.533334h46.933333z" fill="currentColor"></path></svg>', "</a>"].join(""),

            // 跳页区域
            skip: (function () {
                var skipText = typeof config.skipText === "object" ? config.skipText : ["到第", "页", "确定"];
                return ['<span class="laypage-skip">' + skipText[0], '<input type="text" min="1" value="' + config.curr + '" class="laypage-input">', skipText[1] + '<button type="button" class="laypage-btn">' + skipText[2] + "</button>", "</span>"].join("");
            })(),
        };

        return [
            '<div class="laypage laypage-' + (config.theme ? (/^#/.test(config.theme) ? "molv" : config.theme) : "default") + '" id="laypage-' + config.index + '">',
            (function () {
                var plate = [];
                config.layout.forEach(function (item,index) {
                    if (views[item]) {
                        plate.push(views[item]);
                    }
                });
                return plate.join("");
            })(),
            "</div>",
        ].join("");
    };

    /**
     * 跳页的回调
     * @param {*} elem
     * @param {*} isskip
     * @returns
     */
    jump = function (elem, isskip) {
        if (!elem) return;

        var that = this;
        var config = that.config;
        var childs = elem.children;
        var btn = elem.getElementsByTagName("button")[0];
        var input = elem.getElementsByTagName("input")[0];
        var select = elem.getElementsByTagName("select")[0];
        var skip = function () {
            var curr = Number(input.value.replace(/\s|\D/g, ""));
            if (curr) {
                config.curr = curr;
                that.render();
            }
        };

        if (isskip) return skip();

        // 页码
        for (var i = 0, len = childs.length; i < len; i++) {
            if (childs[i].nodeName.toLowerCase() === "a") {
                Laypage.on(childs[i], "click", function () {
                    var curr = Number(this.getAttribute("data-page"));
                    if (curr < 1 || curr > config.pages) return;
                    config.curr = curr;
                    that.render();
                });
            }
        }

        // 条数
        if (select) {
            Laypage.on(select, "change", function () {
                var value = this.value;
                if (config.curr * value > config.count) {
                    config.curr = Math.ceil(config.count / value);
                }
                config.limit = value;
                that.render();
            });
        }

        // 确定
        if (btn) {
            Laypage.on(btn, "click", function () {
                skip();
            });
        }
    };

    /**
     * 输入页数字控制
     * @param {*} elem
     * @returns
     */

    skip = function (elem) {
        if (!elem) return;

        var that = this;
        var input = elem.getElementsByTagName("input")[0];

        if (!input) return;

        // 键盘事件
        Laypage.on(input, "keyup", function (e) {
            var value = this.value;
            var keyCode = e.keyCode;

            if (/^(37|38|39|40)$/.test(keyCode)) return;

            if (/\D/.test(value)) {
                this.value = value.replace(/\D/, "");
            }
            if (keyCode === 13) {
                that.jump(elem, true);
            }
        });
    };

    /**
     * 渲染分页
     * @param {*} load
     */
    render = function (load) {
        var that = this;
        var config = that.config;
        var type = that.type();
        var view = that.view();

        if (type === 2) {
            config.elem && (config.elem.innerHTML = view);
        } else if (type === 3) {
            config.elem.html(view);
        } else {
            if (document.getElementById(config.elem)) {
                document.getElementById(config.elem).innerHTML = view;
            }
        }

        config.jump && config.jump(config, load);

        var elem = document.getElementById("laypage-" + config.index);
        that.jump(elem);

        if (config.hash && !load) {
            location.hash = "!" + config.hash + "=" + config.curr;
        }

        that.skip(elem);
    };
}

// 外部接口
var Laypage = {
    // 分页渲染
    render: function (options) {
        var o = new LaypageClass(options);
        return o.index;
    },
    index: Laypage ? Laypage.index + 10000 : 0,
    on: function (elem, even, fn) {
        elem.attachEvent
            ? elem.attachEvent("on" + even, function (e) {
                  // for ie
                  e.target = e.srcElement;
                  fn.call(elem, e);
              })
            : elem.addEventListener(even, fn, false);
        return this;
    },
};

export default Laypage;
